const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const VerificationCode = sequelize.define('VerificationCode', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  email: {
    type: DataTypes.STRING(100),
    allowNull: false,
    validate: {
      isEmail: {
        msg: '邮箱格式不正确'
      }
    }
  },
  code: {
    type: DataTypes.STRING(6),
    allowNull: false
  },
  type: {
    type: DataTypes.ENUM('register', 'reset_password'),
    allowNull: false
  },
  expiresAt: {
    type: DataTypes.DATE,
    allowNull: false
  },
  isUsed: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    allowNull: false
  }
}, {
  tableName: 'verification_codes',
  indexes: [
    {
      fields: ['email', 'type']
    }
  ]
});

// 生成随机验证码
VerificationCode.generateCode = function() {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// 创建新的验证码
VerificationCode.createCode = async function(email, type) {
  // 先将该邮箱之前的同类型验证码设为已使用
  await this.update(
    { isUsed: true },
    { where: { email, type, isUsed: false } }
  );

  // 创建新的验证码
  const code = this.generateCode();
  const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10分钟有效期

  return await this.create({
    email,
    code,
    type,
    expiresAt
  });
};

// 验证验证码
VerificationCode.verifyCode = async function(email, code, type) {
  const verificationCode = await this.findOne({
    where: {
      email,
      code,
      type,
      isUsed: false,
      expiresAt: {
        [sequelize.Sequelize.Op.gt]: new Date()
      }
    }
  });

  if (!verificationCode) {
    return false;
  }

  // 标记为已使用
  await verificationCode.update({ isUsed: true });
  return true;
};

module.exports = VerificationCode;